package com.haidechizi.leetcode;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: wangdejun
 * @create: 2020-04-16 09:51
 **/
public class _56_合并区间 {

    public int[][] merge(int[][] intervals) {
        if (intervals == null || intervals.length <= 1) {
            return intervals;
        }
        sort(intervals);
        int left = intervals[0][0];
        int right = intervals[0][1];
        List<int[][]> result = new ArrayList<>();
        for (int i = 1; i < intervals.length; i++) {
            if (intervals[i][0] <= right) {
                if(right < intervals[i][1]) {
                    right = intervals[i][1];
                }
            } else {
                int[][] temp = new int[][]{{left, right}};
                result.add(temp);
                left = intervals[i][0];
                right = intervals[i][1];
            }
        }
        int[][] temp = new int[][]{{left, right}};
        result.add(temp);
        int[][] mergeArr = new int[result.size()][2];
        for (int i = 0; i < result.size(); i++) {
            mergeArr[i][0] = result.get(i)[0][0];
            mergeArr[i][1] = result.get(i)[0][1];
        }
        return mergeArr;
    }

    public void sort(int[][] intervals) {
        for (int i = 0; i < intervals.length; i++) {
            for (int j = 0; j < intervals.length - i - 1; j++) {
                if (intervals[j][0] > intervals[j + 1][0]) {
                    int[] temp = intervals[j];
                    intervals[j] = intervals[j + 1];
                    intervals[j + 1] = temp;
                }
            }
        }
    }


}
